package net.unix8.thread;

import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import net.unix8.client.Client;
import net.unix8.share.NetworkShare;
import net.unix8.tool.Tools;
//连接到arm开发板服务器的
public class TaskThread extends Thread{
	private String host;
	private String cmd;
	private ChannelId channel;
	private int id;
	public TaskThread(String host, String cmd, ChannelId channel,int id){
		this.host = host;
		this.cmd = cmd;	
		this.channel = channel;
		this.id = id;
	}
	@Override
    public void run() {
        try {
			new Client(channel, cmd, host, id).connect(host, 4040);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			JSONObject studentJSONObject = new JSONObject();  
			try {  
				studentJSONObject.put("host", host);
				studentJSONObject.put("id", id);  
				studentJSONObject.put("cmd", "ctrl"); 
				studentJSONObject.put("status", false);  
				studentJSONObject.put("data","Host Unreachable");  
			} catch (JSONException e1) {  
				e1.printStackTrace();  
			}  

			Channel remoteChannel = NetworkShare.clientGroup.find(channel);
			if(remoteChannel != null){
				final ByteBuf firstMessage;
				firstMessage = Unpooled.buffer(100);
				firstMessage.writeCharSequence(Tools.encode(studentJSONObject.toString()), Charset.forName("UTF-8"));

				//firstMessage.writeCharSequence(studentJSONObject.toString(), Charset.forName("UTF-8"));
				remoteChannel.writeAndFlush(firstMessage);
			}
		}
	}
}
